#include "mainwindow.h"
#include "prio/detrendIBI_priors.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <prio/coder_array.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    coder::array<double, 2U> dibi;
    coder::array<double, 2U> nibi;
    coder::array<double, 2U> trend;
    double resampleRate_tmp=4;
    // Initialize function 'detrendIBI_priors' input arguments.
    // Initialize function input argument 'ibi'.
    coder::array<double, 2U> ibi;
    QList<double> data=readtxtFile("E:/qtCode/heart-language-laboratory/TestMatlabLib/TestMatlabLib/nibi.txt");
    int len=data.size();
    qDebug()<<"len="<<len;
    ibi.set_size(len/2, 2);
    int t=0;
    for (int idx0{0}; idx0 < len/2; idx0++) {
        for (int idx1{0}; idx1 < 2; idx1++) {
            ibi[idx0 + len/2 * idx1] = data[t++];
        }
    }

    // Call the entry-point 'detrendIBI_priors'.
    // void detrendIBI_priors(const emlrtStack *sp,
    //                    const coder::array<real_T, 2U> &ibi, real_T resampleRate,
    //                    real_T lambda, boolean_T meanCorrection,
    //                    coder::array<real_T, 2U> &dibi,
    //                    coder::array<real_T, 2U> &nibi,
    //                    coder::array<real_T, 2U> &trend);

    const emlrtStack *sp;
    detrendIBI_priors(sp,ibi, resampleRate_tmp, 10,false, dibi, nibi, trend);
    for(int i=0;i<10;i++)
    {
        qDebug()<<"dibi"<<dibi.at(i,1);
        qDebug()<<"nibi"<<nibi.at(i,1);
        qDebug()<<"trend"<<trend.at(i,1);
    }
}


QList<double> MainWindow::readtxtFile(const QString &filePath)
{
    QFile file(filePath);
    QList<double>data;
    coder::array<double, 2U> tmp;
    if (file.open(QIODevice::ReadOnly  | QIODevice::Text)) {
        qDebug() << "打开文件:" << filePath;
        QTextStream in(&file);
        int lineNumber = 0;
        while (!in.atEnd())  {
            lineNumber++;
            QString line = in.readLine().trimmed();
            // 跳过空行
            if (line.isEmpty())  {
                continue;
            }

            // 分割行数据
            QStringList columns = line.split(',',  Qt::SkipEmptyParts);

            // 确保有两列数据
            if (columns.size()  < 2) {
                qDebug() << "第" << lineNumber << "行数据格式错误，需要两列数据";
                continue;
            }

            // 获取两列数据并去除空格
            QString col1 = columns[0].trimmed();
            QString col2 = columns[1].trimmed();
            data.append(col1.toDouble());
            data.append(col2.toDouble());
        }
        file.close();
    }

    return data;
}
